 #include "Zph02.h"

/*宏定义*/
#define SERIAL2_RX 18
#define SERIAL2_TX 19

/*全局变量*/
float pm25 = 0.0;//pm2.5浓度
extern volatile uint8_t manual_open_fan_flag;//风扇自动侦测标志 
                                             //0-自动侦测关闭 1--自动侦测开启 2--自动侦测暂时关闭10分钟后开启
extern volatile uint8_t fan_switch;//风扇开关标志 0--关闭 1--开启
volatile uint8_t pm25_flag = 0;//风扇根据PM2.5而开启关闭 0--关闭 1--开启
extern volatile uint8_t ppb_flag;//风扇根据甲醛而开启关闭 0--关闭 1--开启

/*全局函数*/
void Zph02_Init(void)//ZPH02初始化
{
    Serial2.begin(9600, SERIAL_8N1, SERIAL2_RX, SERIAL2_TX);

    Serial.println("Zph02 Init success");
}

void Read_ZPh02_Data(void)//读取ZE08CH2O数据
{
    static uint8_t idx = 0;
    uint8_t i;
    uint8_t j = 0;
    char zph02_data[9];


    i = Serial2.available();

    if(i == 9)
    {
        while(i--)
        {
            zph02_data[j] = Serial2.read();
            j++;
        }
        Serial2.flush();

        if(zph02_data[0] == 0xFF)
        {
            // for(i = 0; i < sizeof(zph02_data); i++)
            // {
            //     Serial.printf(" %x ",zph02_data[i]);
            // }
            //Serial.printf("%d.%d ",zph02_data[3],zph02_data[4]);
            pm25 =  zph02_data[3] + zph02_data[4] / 100.0;
            pm25 = pm25 / 100.0 * 1000;
            if(idx > 5)
            {
                Update_PM25_To_Aliyun(pm25);
                idx = 0;

                if(manual_open_fan_flag == 1)
                {
                    if(pm25 >= 75.0)
                    {
                        if(fan_switch == 0)
                        {
                           Fan_Open();
                           fan_switch = 1; 
                        }

                        pm25_flag = 1;
                    }
                    else if(pm25 < 75.0)
                    {
                        pm25_flag = 0;
                        
                        if(fan_switch == 1 && ppb_flag == 0)
                        {
                            Fan_Close();
                            fan_switch = 0;
                        }
                    }

                    Update_FanSwitch_To_Aliyun(fan_switch);
                }
                else//手动模式
                {

                }
            }
            else if(idx <= 5)
            {
                idx++;
            }
           
          
            //Serial.printf("%f\r\n",pm25);
            //pm25 = zph02_data[3] + (double)(zph02_data[4] / 100);
            //Serial.printf("pm25:%f\r\n",pm25);
            
            //Serial.println();
        }
    } 
    else if(i > 9)
    {
        while(i--)
        {
            Serial2.read();
        }
        Serial2.flush();
    } 
}
